<?php

namespace app\admin\controller;

use app\admin\model\BankModel;
use app\admin\model\CarModel;
use app\admin\model\DriverModel;
use my\Security;
use think\Db;
use think\Env;
use my\Tools;
use app\admin\model\RegionModel;
use app\admin\model\AdminModel;
use app\admin\controller\ProduceCode;

class Driver extends Base
{
    //protected  $map = ['auth_status'=>1];//只显示通过审核的司机

    protected $driver_model;
    public $auditStatus = array();
    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        $referee_type = [
            1 => '乘客',
            2 => '司机',
            4 => '快车租赁公司',
            5 => '城际车队'
        ];
        //0审核中，1通过，2驳回
        $this->auditStatus = [
            0 => '审核中',
            1 => '通过',
            2 => '驳回'
        ];

        //加盟商名称

        $this->assign('referee_type', $referee_type);
        $this->assign('authTypeList', auth_type());
        $this->assign('authStatusList', auth_status());
        $this->driver_model = new DriverModel();
        //获取省份信息
        $this->region_model = new RegionModel();
        $where = [
            'parent_id' => 1,
            'region_level' => 1
        ];
        $provinceList = $this->region_model->getRegion($where, 'region_id,region_name');
        $this->assign('provinceList', $provinceList);


        $theirList = Db::name('their')->order('their_id desc')->select();
        $this->assign('theirList', $theirList);
        $this->assign('compliance', config('compliance'));
        $this->field = 'a.driver_id,a.driver_name,a.driver_phone,a.auth_status,a.driver_status,a.driver_type,a.referee_id,a.referee_type,a.franchisee_type,a.franchisee_id,a.forbid,a.compliance_type,a.is_header,b.auth_type,c.work_province,c.work_city,b.register_time,b.last_login_time,b.join_time,b.logout_time,c.taxi_pass,c.taxi_certificate_pass,c.comm_pass,c.sail_pass,c.carriage_pass';
    }

    //司机列表
    public function index()
    {
        $page = input('get.page');
        $limit = input('get.limit');
        $driver_type = input('get.driver_type');
        $their_id = input('get.their_id');
        if ($page && $limit) {
            $where=$this->mapData;
            if($their_id>0){
                $where['b.their_id']=$their_id;
            }
            $start = ($page - 1) * $limit;
            $list = Db::name('driver a')
                ->join('their b', 'a.their_id = b.their_id', 'LEFT')
                ->limit($start, $limit)
                ->where($where)
                ->order('driver_id desc')
                ->select();
                
            $count = Db::name('driver a') ->join('their b', 'a.their_id = b.their_id', 'LEFT')->where($where)->count();
            foreach ($list as $key => $value) {
                $list[$key]['register_time'] = !empty($value['register_time']) ? date("Y-m-d H:i", $value['register_time']) : '-';
                $list[$key]['last_login_time'] = !empty($value['last_login_time']) ? date("Y-m-d H:i", $value['last_login_time']) : '-';
                $order_common_count = Db::name('order_common')->where("driver_id=".$value['driver_id']." and order_status in(50)")->count();
                $driver_money = Db::name('driver_money')->where("driver_id=".$value['driver_id'])->value('money');
                $list[$key]['orderNum'] = $order_common_count;
                $list[$key]['money'] =  number_format($driver_money/100,2);
            }
            echo json_encode(array(
                'code' => 0,
                'msg' => $where,
                'count' => $count,
                'data' => $list
            ));
            exit;
        }
        $this->assign('driver_type', $driver_type);
        return view();
    }

    /**
     * 封禁记录
     */
    public function banned()
    {
        $page = input('get.page');
        $limit = input('get.limit');
        if ($page && $limit) {
            $data = input('get.');
            $list = $this->driver_model->getBannedList($page, $limit, $data);
            echo json_encode($list);
            exit;
        }
        return view();
    }
    //司机在线记录
    public function onlineList()
    {
        $page = input('get.page');
        $limit = input('get.limit');
        if ($page && $limit) {
            $data = input('get.');
            $list = $this->driver_model->onlineList($page, $limit, $data);
            echo json_encode($list);
            exit;
        }
        return view();
    }



    //详情
    public function detail()
    {
        $did = input('get.driver_id');
        $where['a.driver_id']=$did;
        $driverCar = Db::name('driver a')
            ->join('car_info b', 'a.their_id = b.their_id', 'LEFT')
            ->where($where)
            ->find();
        $this->assign($driverCar);
        return view();


        $driver = new DriverModel();
        $column = array_merge(get_driver_detail_column(), get_car_img_column());

        unset($column['license']);
        unset($column['permit']);
        unset($column['taxi']);
        unset($column['taxi_certificate']);
        unset($column['body_img']);
        $thumb = config('driver_img_thumb_field');
        $info = $driver->getDriverByDid($did, implode(',', array_keys($column)) . $thumb . ',auth_avatar,a.driver_id');

        if ($info) {
            $info = decode_array($info);

            $config['fields'] = $column;
            $config['info'] = $info;
            $config['auth_type'] = auth_type();
            $config['img'] = array_keys(get_car_img_column());
            switch ($info['auth_avatar']) {
                case 0:
                    $color = 'grey';
                    break;
                case 1:
                    $color = 'fuchsia';
                    break;
                case 2:
                    $color = '#0abfde';
                    break;
                case 3:
                    $color = 'red';
                    break;
                default:
                    break;
            }
            $config['tip'] = "<span style='color: {$color};margin-left: 10px'>(" . auth_status()[$info['auth_avatar']] . ")</span>";

            $this->assign($config);
            return view();
        }
    }
    /**
     * 添加司机个人信息
     * @param string
     * @param int
     * @return string 成功时返回
     */
    public function add()
    {
        if(input('post.')){
            $postData=input('post.');
            $t=array_keys($postData,'');//如果空格不算空，就用这条
            //$t = array_keys(array_map('trim', $postData), '');//如果空格算空，就用这条
            if(count($t)>1) {//有空数据项
                $this->error('信息/图片必须全部填写上传');
            }
            $data['driver_phone'] =$postData['driver_phone'];
            $driverData['driver_phone'] =$postData['driver_phone'];

            $have=Db::name('driver')->where('driver_phone',$driverData['driver_phone'])->find();
            if ($have){
                $this->error('失败,已存在该号码');
            }
            $driverData['driver_status'] = 1;
            $driverData['driver_pass'] = md5('123456');
            $driverData['auth_status'] = 1;
            $driverData['driver_name'] =$postData['driver_name'];
            $driverData['driver_sex'] = 9;
            $driverData['id_number'] =$postData['id_number'];
            $driverData['id_hold'] = $postData['id_hold'];
            $driverData['id_hold_thumb'] = $postData['id_hold_thumb'];
            $driverData['id_front'] = $postData['id_front'];
            $driverData['id_front_thumb'] = $postData['id_front_thumb'];
            $driverData['id_back'] = $postData['id_back'];
            $driverData['id_back_thumb'] = $postData['id_back_thumb'];
            $driverData['auth_type'] = $postData['auth_type'];
            $driverData['register_time'] = time();
            $driverData['their_id'] = $postData['their_id'];
            $driverData['service'] = $postData['service'];
            $driverData['service_thumb'] = $postData['service_thumb'];
            $driverData['valid_time'] = $postData['valid_time'];
            $driverData['license'] = $postData['license'];
            $driverData['license_thumb'] = $postData['license_thumb'];
            $driverData['license_number'] = $postData['license_number'];
            $driverData['license_time'] = $postData['license_time'];

            $driver_id=Db::name('driver')->insertGetId($driverData);

            if($driver_id){
                $drivermoney['driver_id']=$driver_id;
            $driver_money_insertGetId=Db::name('driver_money')->insertGetId($drivermoney);

                $car_info['driver_id'] = $driver_id;
                $car_info['add_time'] = $driverData['register_time'];
                $car_info['vin'] = (input('post.vin'));
                $car_info['car_vin'] =(input('post.car_vin'));
                $car_info['car_plate'] = (input('post.car_plate'));
                $car_info['seats'] = input('post.seats');
                $car_info['car_brand'] = (input('post.car_brand'));
                $car_info['car_model'] = (input('post.car_model'));
                $car_info['car_type'] = (input('post.car_brand').input('post.car_model'));
                $car_info['color'] = (input('post.color'));
                $car_info['owner'] = (input('post.owner'));
                $car_info['register_at'] = strtotime(input('post.register_at'));
                $car_info['taxi_license_number'] = (input('post.taxi_license_number'));
                $car_info['company'] = (input('post.company'));
                $car_info['frame_number'] = (input('post.frame_number'));

                $car_info['work_province'] = input('post.work_province');
                $car_info['work_city'] = input('post.work_city');
                $car_info['work_county'] = input('post.work_county');

                $car_info['permit'] = (input('post.permit'));
                $car_info['permit_thumb'] = (input('post.permit_thumb'));

                $car_info['taxi'] = (input('post.taxi'));
                $car_info['taxi_thumb'] = (input('post.taxi_thumb'));

                $car_info['body_img'] = (input('post.body_img'));
                $car_info['body_img_thumb'] = (input('post.body_img_thumb'));
                $car_info['their_id'] = (input('post.their_id'));
                $res=Db::name('car_info')->insertGetId($car_info);

                return "<script type='application/javascript'>alert('添加成功');parent.window.location.reload();</script>";
            }else{

            }
        }
       return view();
    }
    /**
     * 修改司机个人信息
     * @param string
     * @param int
     * @return string 成功时返回
     */
    public function edit()
    {
        $did = input('get.driver_id');
        if(input('post.')){
            $postData=input('post.');
            $t=array_keys($postData,'');//如果空格不算空，就用这条
            //$t = array_keys(array_map('trim', $postData), '');//如果空格算空，就用这条
            if(count($t)>1) {//有空数据项
                $this->error('信息/图片必须全部填写上传');
            }
            $data['driver_phone'] =$postData['driver_phone'];
            $driverData['driver_phone'] =$postData['driver_phone'];

            $have=Db::name('driver')->where('driver_phone',$driverData['driver_phone'])->find();
            if ($have['driver_id']!=$postData['driver_id']){
                $this->error('失败,已存在该号码');
            }


            $driverData['driver_name'] =$postData['driver_name'];

            $driverData['id_number'] =$postData['id_number'];
            $driverData['id_hold'] = $postData['id_hold'];
            $driverData['id_hold_thumb'] = $postData['id_hold_thumb'];
            $driverData['id_front'] = $postData['id_front'];
            $driverData['id_front_thumb'] = $postData['id_front_thumb'];
            $driverData['id_back'] = $postData['id_back'];
            $driverData['id_back_thumb'] = $postData['id_back_thumb'];
            $driverData['auth_type'] = $postData['auth_type'];

            $driverData['their_id'] = $postData['their_id'];
            $driverData['service'] = $postData['service'];
            $driverData['service_thumb'] = $postData['service_thumb'];
            $driverData['valid_time'] = $postData['valid_time'];
            $driverData['license'] = $postData['license'];
            $driverData['license_thumb'] = $postData['license_thumb'];
            $driverData['license_number'] = $postData['license_number'];
            $driverData['license_time'] = $postData['license_time'];
            $res = Db::name('driver')->where('driver_id', $postData['driver_id'])->update($driverData);
            if($res){
                $car_info['vin'] = (input('post.vin'));
                $car_info['car_vin'] =(input('post.car_vin'));
                $car_info['car_plate'] = (input('post.car_plate'));
                $car_info['seats'] = input('post.seats');
                $car_info['car_brand'] = (input('post.car_brand'));
                $car_info['car_model'] = (input('post.car_model'));
                $car_info['car_type'] = (input('post.car_brand').input('post.car_model'));
                $car_info['color'] = (input('post.color'));
                $car_info['owner'] = (input('post.owner'));
                $car_info['register_at'] = strtotime(input('post.register_at'));
                $car_info['taxi_license_number'] = (input('post.taxi_license_number'));
                $car_info['company'] = (input('post.company'));
                $car_info['frame_number'] = (input('post.frame_number'));

                $car_info['work_province'] = input('post.work_province');
                $car_info['work_city'] = input('post.work_city');
                $car_info['work_county'] = input('post.work_county');

                $car_info['permit'] = (input('post.permit'));
                $car_info['permit_thumb'] = (input('post.permit_thumb'));

                $car_info['taxi'] = (input('post.taxi'));
                $car_info['taxi_thumb'] = (input('post.taxi_thumb'));

                $car_info['body_img'] = (input('post.body_img'));
                $car_info['body_img_thumb'] = (input('post.body_img_thumb'));
                $car_info['their_id'] = (input('post.their_id'));
                $res = Db::name('car_info')->where('driver_id', $postData['driver_id'])->update($car_info);
                return "<script type='application/javascript'>alert('成功');parent.window.location.reload();</script>";
            }
        }else{
            $where['a.driver_id']=$did;
            $driverCar = Db::name('driver a')
                ->join('car_info b', 'a.driver_id = b.driver_id', 'LEFT')
                ->where($where)
                ->find();

            $this->assign('driverCar',$driverCar);

            return view();
        }




    }

    //司机余额列表
    public function money()
    {
        return $this->fetch();
    }

    //司机余额列表
    public function tableMoney()
    {
        echo 11111111;die();
        $page = input('get.page');
        $limit = input('get.limit');
        $driver_type = input('get.driver_type');
        if ($page && $limit) {
            $where=$this->mapData;
            $start = ($page - 1) * $limit;
            $list = Db::name('driver a')
                ->join('their b', 'a.their_id = b.their_id', 'LEFT')
                ->limit($start, $limit)
                ->where($where)
                ->order('driver_id desc')
                ->select();
            $count = Db::name('driver a') ->join('their b', 'a.their_id = b.their_id', 'LEFT')->where($where)->count();

            foreach ($list as $key => $value) {
                $list[$key]['register_time'] = !empty($value['register_time']) ? date("Y-m-d H:i", $value['register_time']) : '-';
                $list[$key]['last_login_time'] = !empty($value['last_login_time']) ? date("Y-m-d H:i", $value['last_login_time']) : '-';
                $count = Db::name('order_common')->where("driver_id=".$value['driver_id']." and order_status in(50)")->count();
                $money = Db::name('driver_money')->where("driver_id=".$value['driver_id'])->value('money');
                $list[$key]['orderNum'] = $count;
                $list[$key]['money'] =  number_format($money/100,2);
            }
            echo json_encode(array(
                'code' => 0,
                'msg' => $where,
                'count' => $count,
                'data' => $list
            ));
            exit;
        }
        $this->assign('driver_type', $driver_type);
        return view();

    }

    //司机车辆信息
    public function carInfo()
    {
        $did = input('post.driver_id');
        //$did = 2073;
        $return['status'] = 0;
        $return['msg'] = '缺少参数';
        if ($did) {
            $column_car = array_merge(get_car_detail_column(), get_car_img_column());
            $column_car = array_diff($column_car, get_driver_detail_column());
            unset($column_car['id_front']);
            unset($column_car['id_back']);
            unset($column_car['id_hold']);
            $thumb_car = config('car_img_thumb_field');
            $car = new CarModel();
            $map['a.driver_id'] = $did;
            $map['a.record_status'] = 1;
            $car_info = $car->searchCarList($map, implode(',', array_keys($column_car)) . $thumb_car . ',auth_type as att');
            if ($car_info['att'] == 1) {
                unset($column_car['taxi']);
                unset($column_car['taxi_certificate']);
            }
            $config['car_fields'] = $column_car;
            $config['car_info'] = decode_array_2($car_info);
            $config['auth_type'] = auth_type();
            $config['img'] = array_keys(get_car_img_column());
            $this->assign($config);
            $return['html'] = $this->fetch();
            $return['status'] = 1;
            $return['msg'] = 'ok';
        }
        return json($return);
    }

    /**
     * 汽车车辆修改
     * @param string
     * @param int
     * @return string 成功时返回
     */
    public function carInfoEdit()
    {
        $did = input('post.driver_id');
        $return['status'] = 0;
        $return['msg'] = '缺少参数';
        if ($did) {
            $column_car = array_merge(get_car_detail_column(), get_car_img_column());
            $column_car = array_diff($column_car, get_driver_detail_column());
            unset($column_car['id_front']);
            unset($column_car['id_back']);
            unset($column_car['id_hold']);
            $thumb_car = config('car_img_thumb_field');
            $car = new CarModel();
            $map['a.driver_id'] = $did;
            $map['a.record_status'] = 1;
            $car_info = $car->searchCar($map, 'car_id,' . implode(',', array_keys($column_car)) . $thumb_car . ',auth_type as att');
            if ($car_info['att'] == 1) {
                unset($column_car['taxi']);
                unset($column_car['taxi_certificate']);
            }
            $config['car_fields'] = $column_car;
            $config['car_info'] = decode_array($car_info);
            $config['auth_type'] = auth_type();
            $config['img'] = array_keys(get_car_img_column());
            $this->assign($config);
            $return['html'] = $this->fetch();
            $return['status'] = 1;
            $return['msg'] = 'ok';
        }
        return json($return);
    }

    //某位司机审核信息
    public function authInfo()
    {
        $did = input('post.driver_id');
        $return['status'] = 0;
        $return['msg'] = '缺少参数';
        if ($did) {
            $config['url'] = url('tableAuth', array('driver_id' => $did));
            $this->assign($config);
            $return['html'] = $this->fetch();
            $return['status'] = 1;
            $return['msg'] = 'ok';
        }
        return json($return);
    }

    public function tableAuth()
    {
        $page = input('get.page');
        $limit = input('get.limit');
        $map['driver_id'] = input('get.driver_id');
        $res = Db::name('driver_auth_record a')->join('admin b', 'a.admin_id=b.admin_id', 'LEFT')
            ->field('a.*,b.user_name')->where($map)->order('a.record_id desc')->page($page, $limit)->select();
        $count = db('driver_auth_record')->where($map)->count();
        foreach ($res as $key => $val) {
            foreach ($val as $k => $v) {
                if (strpos($k, '_time') !== false) {
                    $res[$key][$k] = date('Y-m-d H:i:s', $v);
                } elseif ($k == 'record_type') {
                    $res[$key][$k] = record_type()[$v];
                } elseif ($k == 'result') {
                    $res[$key][$k] = $v == 1 ? '是' : '否';
                }
            }
        }
        echo json_encode(array(
            'code' => 0,
            'msg' => '',
            'limit' => $limit,
            'count' => $count,
            'data' => $res
        ));
    }

    //司机银行卡信息
    public function driverBank()
    {
        $map['a.driver_id'] = input('get.driver_id');
        $model_bank = new BankModel();
        $res = $model_bank->getDriverBankList($map, false);
        $res = decode_array($res);
        if (empty($res)) {
            return "<script>alert('暂未绑定银行卡');</script>";
        }
        $this->assign($res);
        return view();
    }

    //司机信息补录
    public function supplement()
    {
        $driver_id = input('get.driver_id');
        $info = Db::table('xm_driver_info_supplement')->where('driver_id', $driver_id)->find();
        if ($info) {
            foreach ($info as $key => $value) {
                switch ($key) {
                    case 'driver_id':
                        break;
                    case 'sex' :
                        break;
                    case 'service_type':
                        break;
                    case 'is_merry':
                        break;
                    case 'language_level_enum':
                        break;
                    case 'education_enum':
                        break;
                    case 'wyc_service_type_enum':
                        break;
                    case 'wyc_is_taxi_driver_enum':
                        break;
                    case 'wyc_is_full_time_enum':
                        break;
                    case 'traffic_violation_times':
                        break;
                    case 'nationality':
                        break;
                    default:
                        $info[$key] = Security::decrypt($value);
                }
            }
        } else {
            $info['driver_id'] = $driver_id;
            $info['service_type'] = 1;
        }

        $this->assign('info', $info);
        return $this->fetch();
    }

    public function supplement_submits()
    {
        $supplement = input('post.');
        $arr = explode('&', $supplement['data']);//转成数组
        $supplement_data = array();
        foreach ($arr as $k => $v) {
            $arr = explode('=', $v);
            $supplement_data[$arr[0]] = $arr[1];
        }
        $driver_id = $supplement_data['driver_id'];
        if (strtotime($supplement_data['contract_valid_end']) <= strtotime($supplement_data['contract_valid_start'])) {
            echo json_encode(array('code' => 2, 'msg' => '合同（协议）起始时间不能小于失效时间！'));
            exit();
        }
        if (strtotime($supplement_data['certificate_valid_end']) <= strtotime($supplement_data['certificate_valid_start'])) {
            echo json_encode(array('code' => 3, 'msg' => '资格证起始时间不能小于失效时间！'));
            exit();
        }
        if ($driver_id) {
            foreach ($supplement_data as $key => $value) {
                switch ($key) {
                    case 'driver_id':
                        break;
                    case 'sex' :
                        break;
                    case 'service_type':
                        break;
                    case 'is_merry':
                        break;
                    case 'language_level_enum':
                        break;
                    case 'education_enum':
                        break;
                    case 'wyc_service_type_enum':
                        break;
                    case 'wyc_is_taxi_driver_enum':
                        break;
                    case 'wyc_is_full_time_enum':
                        break;
                    case 'traffic_violation_times':
                        break;
                    case 'nationality':
                        break;
                    default:
                        $supplement_data[$key] = Security::encrypt($value);
                }
            }
            $info = Db::table('xm_driver_info_supplement')->where('driver_id', $driver_id)->find();
            if ($info) {
                $res = Db::table('xm_driver_info_supplement')->where('driver_id', $info['driver_id'])->update($supplement_data);
            } else {
                $res = Db::table('xm_driver_info_supplement')->insert($supplement_data);
            }
            if ($res) {
                echo json_encode(array('code' => 1, 'msg' => '操作成功！'));
                exit();
            } else {
                echo json_encode(array('code' => 0, 'msg' => '操作失败！'));
                exit();
            }
        }
    }


    public function ajax_supplement()
    {
        $supplement = input('post.');
        $arr = explode('&', $supplement['data']);//转成数组
        $supplement_data = array();
        foreach ($arr as $k => $v) {
            $arr = explode('=', $v);
            $supplement_data[$arr[0]] = $arr[1];
        }
        $driver_id = $supplement_data['driver_id'];
        //提交驾驶员基本信息 到java交通部接口
        $data_driver_info = Db::table('xm_driver_info i')
            ->join(['xm_driver_base' => 'b'], 'i.driver_id = b.driver_id', 'LEFT')
            ->field('i.*,b.driver_phone')->where('i.driver_id', $driver_id)->find();
        $data_address = json_decode(ip_local_info($data_driver_info['register_ip']), true)['data']['city_id'];
        if ($data_address == 'local') {
            $data_address = 340100;  //合肥城市编码code
        }
        //组装数据
        $post_data = [];
        $post_data['CompanyId'] = "3401HMKJ8P2R";
        $post_data['Address'] = $data_address;
        $post_data['DriverPhone'] = Security::decrypt($data_driver_info['driver_phone']);
        $post_data['DriverGender'] = $supplement_data['sex'];
        $post_data['DriverBirthday'] = date('Ymd', strtotime($supplement_data['birthday']));
        $post_data['DriverNation'] = $supplement_data['nationality'];
        $post_data['DriverContactAddress'] = $supplement_data['mailing_address'];
        $post_data['LicenseId'] = Security::decrypt($data_driver_info['license_number']);
        $post_data['GetDriverLicenseDate'] = date('Ymd', $data_driver_info['license_time']);
        $post_data['DriverLicenseOn'] = date('Ymd', $data_driver_info['license_time']);
        $post_data['DriverLicenseOff'] = date('Ymd', $data_driver_info['valid_time']);
        $post_data['TaxiDriver'] = $supplement_data['service_type'] == 2 ? 1 : 0;   //是否是巡游驾驶员  1是  0否
        $post_data['CertificateNo'] = $supplement_data['qualifications_number'];
        $post_data['NetworkCarIssueOrganization'] = $supplement_data['issue_agency'];
        $post_data['NetworkCarIssueDate'] = date('Ymd', strtotime($supplement_data['issue_date']));
        $post_data['GetNetworkCarProofDate'] = date('Ymd', strtotime($supplement_data['first_receive_date']));
        $post_data['NetworkCarProofOn'] = date('Ymd', strtotime($supplement_data['certificate_valid_start']));
        $post_data['NetworkCarProofOff'] = date('Ymd', strtotime($supplement_data['certificate_valid_end']));
        $post_data['RegisterDate'] = date('Ymd', strtotime($supplement_data['certificate_valid_end']));
        $post_data['CommercialType'] = $supplement_data['service_type'];
        $post_data['ContractCompany'] = $supplement_data['sign_company'];
        $post_data['ContractOn'] = date('Ymd', strtotime($supplement_data['contract_valid_start']));
        $post_data['ContractOff'] = date('Ymd', strtotime($supplement_data['contract_valid_end']));
        $post_data['State'] = 0;
        $post_data['Flag'] = 1;
        $post_data['UpdateTime'] = date('YmdHis', time());
        if ($driver_id) {
            //提交url 到java接口
            $post_url = Env::get('javaTraffic' . ENV . '_host') . "/410";
            $res = Tools::request_post($post_url, json_encode($post_data));
            if ($res == 200) {
                echo json_encode(array('code' => 1, 'msg' => 'success'));
                exit();
            } else {
                echo json_encode(array('code' => 0, 'msg' => 'error'));
                exit();
            }
        }
    }

    //司机封禁页面
    public function forbid_info()
    {
        $driver_id = input('get.driver_id');
        $this->assign('driver_id', $driver_id);
        return $this->fetch();
    }

    // 封禁/解封
    //driver_status司机状态0: 已注册,1: 正常,2: 不接单,3: 不能登录
    //forbid 是否被封禁 1封禁,2正常
    public function ajax_forbid()
    {
        $driver_id = input('post.driver_id');
        $act = input('post.act');

        if ($act == 'unforbid') {
            if ($driver_id) {
                $res = Db::name('driver')->where('driver_id', $driver_id)->update(['forbid' => 2, 'forbid_time_end' => time(), 'forbid_content' => '已解封']);
                if ($res) {
                    //Db::name('driver_banned_record')->insertGetId(['driver_id' => $driver_id, 'banned_type' => 2, 'banned_cause' => '客服已解封', 'create_time' => time()]);
                    return json(['code' => 1, 'msg' => '解除封禁成功']);
                } else {
                    return json(['code' => 2, 'msg' => '解除封禁失败']);
                }
            }
        } else {
            if ($driver_id) {
                $forbid_type = input('post.forbid_type');
                $forbidArr = [
                    'forbid_content' => input('post.forbid_content'),
                    'forbid' => $forbid_type,
                    'forbid_time_start' => time(),
                    'token' => md5('123456' . $driver_id),
                    'forbid_time_end' => $forbid_type == 3 ? strtotime(input('post.forbid_time_end')) : strtotime("2099-12-31 23:59:59")
                ];

                if ($forbidArr['forbid_time_end'] < time()) {
                    return json(['code' => 2, 'msg' => '封禁时间小于当前时间,请重新选择']);
                    die;
                }
                $res = Db::name('driver')->where('driver_id', $driver_id)->update($forbidArr);
                if ($res) {
                    //查询司机手机号码
                    /*$driver_phone = Db::name('driver_base')->where(['driver_id' => $driver_id])->value('driver_phone');
                    //发送短信封禁成功
                    Tools::sendMes(Security::decrypt($driver_phone), date("Y-m-d H:i:s", $forbidArr['forbid_time_end']), 42);
                    Db::name('driver_banned_record')->insertGetId(['driver_id' => $driver_id, 'banned_type' => 1, 'banned_cause' => input('post.forbid_content'), 'create_time' => time()]);
                    //发送站内信息
                    $content = "您的账号已被封禁，暂时无法接单，封禁原因：" . input('post.forbid_content') . "，解封时间：" . date("Y-m-d H:i:s", $forbidArr['forbid_time_end']);
                    $mes_id = Db::name('driver_message')->insertGetId(['mes_type' => 1, 'title' => '司机封禁', 'content' => $content, 'send_time' => time()]);
                    Db::name('driver_mes_relation')->insertGetId(['driver_id' => $driver_id, 'mes_id' => $mes_id, 'is_read' => 2]);*/
                    return json(['code' => 1, 'msg' => '封禁成功']);
                } else {
                    return json(['code' => 2, 'msg' => '封禁失败']);
                }
            }
        }
    }

    // 升级城际司机
    public function ajax_driver_type()
    {
        $driver_id = input('post.driver_id');
        $act = input('post.act');
        if ($act == 'undriver_type') {
            if ($driver_id) {
                //检测城际司机 是否 已分配车队
                $is_blongs_fleet = Db::table('xm_driver_base')->field('franchisee_type,franchisee_id')->where(['driver_id' => $driver_id])->find();

                if ($is_blongs_fleet['franchisee_type'] == 5) {  //已分配车队 禁止降级
                    return json(['code' => 2, 'msg' => '已分配车队，禁止降级']);
                }

                $res = Db::table('xm_driver_base')->where('driver_id', $driver_id)->update(['driver_type' => 1]);
                if ($res) {
                    return json(['code' => 1, 'msg' => '降级城际司机成功']);
                } else {
                    return json(['code' => 2, 'msg' => '降级城际司机失败']);
                }
            }
        } else {
            if ($driver_id) {
                $res = Db::table('xm_driver_base')->where('driver_id', $driver_id)->update(['driver_type' => 2]);
                if ($res) {
                    return json(['code' => 1, 'msg' => '升级城际司机成功']);
                } else {
                    return json(['code' => 2, 'msg' => '升级城际司机失败']);
                }
            }
        }
    }
    /**
     * 流水列表
     */
    public function driverFlowList()
    {
        $page = input('get.page');
        $limit = input('get.limit');
        if ($page && $limit) {
            $map=$this->mapData;
            $field = 'r.*,a.*';
            $res = Db::table('xm_driver_wallet r')
                ->field($field)
                ->join(['xm_driver'=>'a'], 'a.driver_id = r.driver_id', 'LEFT')
                ->where($map)
                ->page($page,$limit)
                ->order('r.id DESC')
                ->select();

            $count = Db::table('xm_driver_wallet r')
                ->join(['xm_driver'=>'a'], 'a.driver_id = r.driver_id', 'LEFT')
                ->where($map)
                ->count();

            foreach($res as $key => $value) {
                switch ($value['type']) {
                    case 1 : //收入
                        $res[$key]['record_type'] = '收入';
                        $res[$key]['money'] = '+'. sprintf("%.2f", $value['money'] / 100);
                        $order_sn_res = Db::table('xm_order_common')->field('order_sn')->where('common_id', $value['common_id'])->find();
                        $res[$key]['order_sn'] = $order_sn_res['order_sn'];

                        break;
                    case 2 : //提现
                        $res[$key]['record_type'] = '提现';
                        $res[$key]['money'] = '-'. sprintf("%.2f", $value['money'] / 100);
                        $res[$key]['order_sn'] = $value['out_biz_no'];
                        $res[$key]['approve'] = $this->auditStatus[$value['audit_status']];
                        break;
                    default:;
                }
                if(empty($value['add_time'])) {
                    $res[$key]['add_time'] = '';
                } else {
                    $res[$key]['add_time'] = date('Y-m-d H:i:s', $value['add_time']);
                }
            }

            echo json_encode(array(
                'code' => 0,
                'msg' => '',
                'count' => $count,
                'data' => $res
            ));
            exit;
        }
        return view();

    }
    //司机批量分配加盟商
    public function batch_distribute()
    {
        $dataInfo = input('post.');
        if (!empty($dataInfo)) {
            //查询加盟商信息
            $franchiseeList =Db::table('xm_their')->select();
            if (empty($franchiseeList)) {
                $franchiseeInfo = 0;
            } else {
                $html = '';
                foreach ($franchiseeList as $key => $value) {
                    $html .= "<input type='radio' name='their_id' value='" . $value['their_id'] . "' title='" . $value['their_name'] . "'";
                    if ($key == 0) {
                        $html .= " checked";
                    }
                    $html .= ">";
                }
                $franchiseeInfo = $html;
            }
            //查询司机信息
            $where['a.driver_status'] = 1;
            $driverList = Db::name('driver a')
                ->where($where)->field('a.driver_id,a.driver_name,a.franchisee_id')->order('a.driver_id desc')->select();
            foreach ($driverList as $key => $value) {
                if (!empty($value['franchisee_id'])) {
                    unset($driverList[$key]);
                }
            }
            if (!empty($driverList)) {
                $str = '';
                foreach ($driverList as $key => $value) {
                    $str .= "<input type='checkbox' name='driver_id[]' value='" . $value['driver_id'] . "' title='" . $value['driver_name'] . "' class='item_child'>";
                }
            } else {
                $str = 0;
            }
            echo $franchiseeInfo . "|" . $str;
            die;
        }
        return view();
    }

    //司机-批量分配加盟商数据操作入库
    public function batch_driverInfo()
    {
        $data = input('post.');
        if (empty($data['province_id']) || empty($data['city_id'])) {
            echo ajax_error('请选择城市信息');
            die;
        }
        if (empty($data['driver_id'])) {
            echo ajax_error('请选择分配的司机信息');
            die;
        }
        if (empty($data['franchisee_id'])) {
            echo ajax_error('请选择分配的加盟商信息');
            die;
        }
        foreach ($data['driver_id'] as $key => $value) {
            //查询司机类型 快车 - 城际
            $driver_type = Db::name('driver_base')->where(['driver_id' => $value])->value('driver_type');
            if (empty($driver_type) || $driver_type == 1) {
                Db::name('driver_base')->where(['driver_id' => $value])->update(['franchisee_type' => 4, 'franchisee_id' => $data['franchisee_id']]);
            } else {
                Db::name('driver_base')->where(['driver_id' => $value])->update(['franchisee_type' => 5, 'franchisee_id' => $data['franchisee_id']]);
            }
        }
        echo ajax_success('分配成功');
        die;
    }

    //司机信息-分配 快车租赁公司 / 城际车队
    public function distribute()
    {
        $driver_id = input('get.driver_id');
        $driver_type = input('get.driver_type');
        $distributeInfo = input('post.');
        $franchiseeList =Db::table('xm_their')->select();
        $their_id = Db::name('driver')->where(['driver_id' => $driver_id])->value('their_id');
        $this->assign('their_id', $their_id);
        $this->assign('driver_id', $driver_id);
        $this->assign('franchiseeList', $franchiseeList);
        if (!empty($distributeInfo)) {

            Db::name('driver')->where(['driver_id' => $distributeInfo['driver_id']])->update(['their_id' => $distributeInfo['their_id']]);
            Db::name('car_info')->where(['driver_id' => $distributeInfo['driver_id']])->update(['their_id' => $distributeInfo['their_id']]);
            echo ajax_success('分配成功');
            die;
        }
        /*if (!empty($distributeInfo)) {

            if ($distributeInfo['driver_type'] == 1) { //快车司机
                Db::name('driver')->where(['driver_id' => $distributeInfo['driver_id']])->update(['franchisee_type' => 4, 'franchisee_id' => $distributeInfo['franchisee_id']]);
            } elseif ($distributeInfo['driver_type'] == 2) { //城际司机
                Db::name('driver_base')->where(['driver_id' => $distributeInfo['driver_id']])->update(['franchisee_type' => 5, 'franchisee_id' => $distributeInfo['franchisee_id']]);
            }
            echo ajax_success('分配成功');
            die;
        } else {
            //查询司机-相关信息（认证城市）
            $carInfo = Db::name('car_info')->where(['driver_id' => $driver_id])->field('work_province,work_city')->find();

            $franchiseeList = '';
            if ($driver_type == 1) { //快车司机
                //通过司机认证城市 - 查找对应加盟商
                $franchiseeList = Db::connect('db2')->table('franchisee')->where(['province_id' => $carInfo['work_province'], 'city_id' => $carInfo['work_city'], 'is_delete' => 0])->field('id,name')->select();
            } elseif ($driver_type == 2) { //城际司机
                //通过司机认证城市 - 查找对应加盟商
                $franchiseeList = Db::connect('db2')->table('fleet')->where(['province_id' => $carInfo['work_province'], 'city_id' => $carInfo['work_city'], 'is_delete' => 0])->field('id,name')->select();
            }
            $this->assign('franchiseeList', $franchiseeList);
            $this->assign('driver_id', $driver_id);
            //查询司机分配信息
            $franchisee_id = Db::name('driver_base')->where(['driver_id' => $driver_id])->value('franchisee_id');
            $this->assign('franchisee_id', $franchisee_id);
            $this->assign('driver_type', $driver_type);
        }*/
        return view();
    }

    //加盟商分配验证问题
    public function is_verify()
    {
        $driver_id = input('post.driver_id');
        //查询司机认证信息是否通过
        $auth_status = Db::name('driver')->where(['driver_id' => $driver_id])->value('driver_status');
        if ($auth_status == 1) {
            return ['code' => 1, 'msg' => ''];
            die;
        } else {
            return ['code' => 2, 'msg' => '司机认证通过-才可分配'];
            die;
        }
    }

    //人脸识别重置
    public function ajax_face()
    {
        $driver_id = input('post.driver_id');
        //查询是否认证通过
        $auth_status = Db::name('driver_base')->where(['driver_id' => $driver_id])->value('auth_status');
        if ($auth_status != 1) {
            echo ajax_error('该司机还未认证成功,无法重置');
            die;
        }
        $driverInfo = Db::name('driver_info')->where(['driver_id' => $driver_id])->field('face_base,face_status')->find();
        if (!empty($driverInfo)) {
            Db::name('driver_info')->where(['driver_id' => $driver_id])->update(['face_status' => 2]);
            echo ajax_success('人脸识别信息重置成功');
            die;
        } else {
            echo ajax_error('该司机未提交人脸识别信息,无法重置');
            die;
        }
    }

    //城际司机列表
    /*public function interDriverList()
    {
        $page   = input('get.page');
        $limit  = input('get.limit');
        if($page && $limit){
            $data = input('get.');
            $data['driver_type_info'] = 2;
            $list = $this->driver_model->getDriverList($page,$limit,$data,$this->field);
            echo json_encode($list);exit;
        }
        return view();
    }*/

    // 升级 / 降级 城际车队队长
    public function ajax_header()
    {
        $driver_id = input('post.driver_id');
        $act = input('post.act');
        if ($act == 'up_header') {
            if ($driver_id) {
                $res = Db::name('driver_base')->where('driver_id', $driver_id)->update(['is_header' => 1]);
                if ($res) {
                    return json(['code' => 1, 'msg' => '升级队长成功！']);
                } else {
                    return json(['code' => 2, 'msg' => '升级队长失败！']);
                }
            }
        } else {
            if ($driver_id) {
                $res = Db::name('driver_base')->where('driver_id', $driver_id)->update(['is_header' => 0]);
                if ($res) {
                    return json(['code' => 1, 'msg' => '撤销队长职务成功']);
                } else {
                    return json(['code' => 2, 'msg' => '撤销队长职务失败']);
                }
            }
        }
    }

    //生成二维码
    public function franchisee_code(){
        $driverId = input('get.driverId');
        //信息是否存在
        $franchiseeInfo = Db::name('driver_base')->where(['driver_id'=>$driverId])->find();
        if(empty($franchiseeInfo)){
            $this->error('参数错误', '', '', 1);
        }
        //查询司机是否为快车司机
        $driver_type = Db::name('driver_base')->where('driver_id', $driverId)->value('driver_type');
        //生成小程序二维码
        $produce_code=new ProduceCode();
        $result=$produce_code->produce_code($driverId,$driver_type);
        $this->assign('franchiseeInfo',$result);
        return $this->fetch();
    }
}
